<template>
  <div style="height: 100%;">
    <div class="custBox">
      <div class="operation">
        <div class="operation_left">
          <span v-show="select_num == 0">共{{total}}个客户</span>
          <span v-show="select_num > 0">已选中{{select_num}}个</span>

          <el-button size="mini" style="margin: 0 5px" @click="senMail" :disabled="select_num == 0"
                     v-if="jurisdiction.customer_senMail">发送邮件
          </el-button>
          <el-button size="mini" style="margin: 0 5px" @click="dealingsMail" :disabled="edit_boolean"
                     v-if="jurisdiction.customer_exchange">来往邮件
          </el-button>
          <el-button size="mini" @click="editlog()" :disabled="edit_boolean" style="margin: 0 5px"
                     v-if="jurisdiction.customer_edit">编辑
          </el-button>

          <el-cascader
            size="mini"
            :options="custTypeOptions"
            style="width:100px"
            placeholder="移动到"
            v-if="jurisdiction.customer_move"
            :show-all-levels="false"
            :props="props"
            v-model="groupId"
            @visible-change="changeGroup"></el-cascader>

          <el-dropdown trigger="click" @command="changeSelect" style="margin: 0 5px" placement="bottom-start"
                       v-show="jurisdiction.customer_senMail || jurisdiction.customer_exchange || jurisdiction.customer_merge ||
 jurisdiction.customer_share || jurisdiction.customer_transfer || jurisdiction.customer_cancel || jurisdiction.customer_delete">
            <el-button class="el-dropdown-link" size="mini">
              更多 <i class="el-icon-caret-bottom"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" placement="bottom-start">
              <el-dropdown-item command="2" v-show="jurisdiction.customer_share">标记为</el-dropdown-item>
              <el-dropdown-item command="3" :disabled="select_num < 2" v-show="jurisdiction.customer_merge">合并
              </el-dropdown-item>
              <el-dropdown-item command="4" v-show="jurisdiction.customer_share">共享</el-dropdown-item>
              <el-dropdown-item command="5" v-show="jurisdiction.customer_transfer">转移</el-dropdown-item>
              <el-dropdown-item command="6" v-show="jurisdiction.customer_cancel">取消跟进</el-dropdown-item>
              <el-dropdown-item command="7" v-show="jurisdiction.customer_delete">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="operation_right search">
          <el-autocomplete
            size="mini"
            class="inline-input"
            style="width:220px;margin: 0 10px"
            v-model="input"
            @keyup.enter.native="search"
            @change="replace"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="请输入客户名称/联系人/邮箱查询">
            <el-button slot="append" style="cursor: pointer;" @click="search">
              <i class="el-icon-search"></i>
            </el-button>
          </el-autocomplete>

          <el-button size="mini" @click="advancedSearch()">高级搜索</el-button>

          <el-button size="mini" @click="$refs.dialogImport.init()">客户导入</el-button>

          <el-button size="mini" @click="showlog()" style="margin-left: 10px" v-if="jurisdiction.customer_add"
                     type="primary" plain>+新增客户
          </el-button>
        </div>
      </div>
      <div style="background-color:white">
        <div class="btns" v-show="senior">
          <div style="width: 96px;padding-top: 7px">
            <span style="color:#232323">标签：</span>
            <label style="margin:0 4px;">
              <input type="checkbox" style="height:1px;width:1px;display:none">
              <span class="lable_checkbox" @click="checkbox($event, 'lable', markList)" onselectstart="return false"
                    :class="lables.length == markList.length ? 'checkbox_active' : ''"></span>
            </label> <span>全部</span>
          </div>
          <div>
            <span class="btn_item_lable" v-for="(item,index) in markList"
                  :class="lables.includes(item.id) ? 'activeBtn': ''" :key="index" onselectstart="return false"
                  @click="active($event, 'label', item.id)">{{item.markName}}</span>
          </div>
        </div>
      </div>
      <el-dialog
        :visible.sync="centerDialogVisible"
        width="300px"
        append-to-body
        :show-close="true"
        @close="closeCustShow"
        center>
          <span slot="title" class="dialog-title">
            客户列表显示字段设置
          </span>
        <div style="height: 300px">
          <el-checkbox-group v-model="copyCheckList" :min="1" @change="changeCheck">
            <div v-for="(value,index3) in showlist" :key="index3" style="padding-left: 85px;margin: 5px 0">
              <el-checkbox :label="value.name" :disabled="value.name =='公司名称' "></el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeCustShow" size="small" type="primary" plain>取 消</el-button>
            <el-button type="primary" @click="custShow" :loading="loading" size="small">保存</el-button>
          </span>
      </el-dialog>
      <div class="table_box">
        <div class="icon icon_left">
          <span class="icon-shaixuan" @click="centerDialogVisible = true"></span>
        </div>
        <el-table
          v-show="load"
          :header-row-style="{background:'#EAF0F6'}"
          ref="multipleTable"
          :data="tableData"
          @selection-change='selectList'
          tooltip-effect="dark"
          style="width: 100%"
          :height="tableHeight"
          class="table"
          @sort-change="sortChange"
          @row-click="preview">
          <el-table-column
            type="selection"
            :fixed="true"
            width="55">
          </el-table-column>
          <template v-for="(col, index) in headerList">
            <el-table-column
              :width="col.field == 'light' ? 80 : 200"
              :label="col.name"
            >
              <template slot-scope="scope">
                <tableTemplate :col="scope.row" :label="col.field" :jurisdiction="jurisdiction" @jump="toDetail" @handleChange="changeRate" @handleCancel="unlabel" @handleSign="star"></tableTemplate>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            width="40"
            fixed="right"
            title="列表显示字段">
          </el-table-column>
          <div slot="empty" style="width: 100%;text-align: left;margin-lrft:-250px">
            <div>
              <img :src="empty" alt="" style="width: 250px"/>
            </div>
          </div>
        </el-table>
      </div>
      <div class="footer">
        <el-pagination align="right" class="fixed"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="nowPage"
                       :page-sizes="[10, 20, 30, 50]"
                       :page-size="nowSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>

      <el-dialog
        :visible.sync="markDialog"
        width="500px" align="center"
        style="font-size: 13px"
        :close-on-click-modal="false"
        @close="cancelMark"
        center
        append-to-body>
        <span slot="title" class="dialog-title">
          <span style="color:#2A97F9">标记客户</span>
        </span>
        <div style="margin-bottom:20px">
          <div class="flex">
            <span>标记为：</span>
            <el-select v-model="markArr" multiple placeholder="请选择" size="small" @change="openAddMark"
                       v-if="markDialog">
              <el-option
                v-for="item in lableList"
                :key="item.id"
                :label="item.markName"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelMark" size="small">取 消</el-button>
          <el-button type="primary" @click="custSaveMark" :loading="loading" size="small">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 弹窗新增客户-->
      <editCompany ref="editCompany" @updata="updataCompany"
                   :email="[]" :title="editCom_title" :id="custId" :defaultType="typeId"></editCompany>
      <el-dialog
        :visible.sync="signDialog"
        width="500px"
        center
        :close-on-click-modal="false"
        append-to-body>
        <span slot="title" class="dialog-title">
          <span style="color:#2A97F9">合并客户</span>
        </span>
        <div class="center_left">
          <span style="margin-right:20px">待合并客户:</span>
          <div style="padding-left:40px;margin-top: 5px">

            <el-radio-group v-model="priKey">
              <el-radio v-for="(item, index) in selectData" :key="index" :label="item.fullname">{{item.fullname}}
              </el-radio>
            </el-radio-group>

          </div>
        </div>
        <div style="margin-top:20px" class="center_left">
          <span class="el-icon-warning-outline"></span>
          <span>   客户资料冲突时，将会以主客户（{{priKey}}） 的资料为准！</span>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="signDialog = false" size="small">取 消</el-button>
          <el-button type="primary" @click="mergeCust" :loading="loading" size="small">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 转移客户 -->
      <el-dialog :visible.sync="transferDialog" center append-to-body width="480px" :close-on-click-modal="false"
                 style="font-size:13px" :before-close="cancelTransfer">
        <p slot="title" class="dialog-title">转移客户</p>

        <div class="operation_box">
          <div class="operation_information">将这（{{selectData.length}}位）客户转移给：</div>
          <div>
            <el-select v-model="transferArr" placeholder="请选择" size="small">
              <el-option
                v-for="item in userTree"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="cust_content">
          <div style="flex: 0 0 100px">
            <span>被转移的客户：</span>
          </div>
          <div>
                <span v-for="(item, index) in selectData" :key="index">
              <span v-if="index > 0">.</span>
              {{item.fullname}}</span>
          </div>
        </div>

        <p style="line-height: 18px">
          <span>
            <span class="icon-iconfontxiaogantanhao" style="margin-right: 5px"></span>
            客户转移给他人后，将会从我的客户列表中删除，对方将可见该客户的全部资料。</span>
        </p>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelTransfer" size="small">取 消</el-button>
          <el-button type="primary" @click="transferCust" :loading="loading" size="small">转 移</el-button>
        </div>
      </el-dialog>

      <!-- 共享客户 -->
      <el-dialog :visible.sync="shareDialog" center append-to-body width="500px" :close-on-click-modal="false"
                 style="font-size:13px" :before-close="cancelShare">
         <span slot="title" class="dialog-title">
          <span style="color:#2A97F9">共享客户</span>
        </span>
        <div class="operation_box">
          <div class="operation_information">将这（{{selectData.length}}位）客户共享给：</div>
          <div>
            <el-select v-model="shareArr" multiple placeholder="请选择" size="small">
              <el-option
                v-for="item in userTree"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="cust_content">
          <div style="flex: 0 0 100px">
            <span>被共享的客户：</span>
          </div>
          <div>
            <span v-for="(item, index) in selectData" :key="index" :label="item.fullname">
              <span v-if="index > 0">.</span>
              {{item.fullname}}</span>
          </div>
        </div>
        <p>
          <span class="icon-iconfontxiaogantanhao"></span>
          <span>客户共享后，将同时出现在我和被共享人的客户列表中。客户资料共享。</span>
        </p>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelShare" size="small">取 消</el-button>
          <el-button type="primary" @click="sharedCust" :loading="loading" size="small">确 定</el-button>
        </div>
      </el-dialog>


      <el-dialog :visible.sync="label_show" center append-to-body width="415px" :close-on-click-modal="false"
                 style="font-size:13px" @close="cancelLabel">
        <p slot="title" class="dialog-title">标签</p>
        <div class="flex">
          <span>标签名称：</span>
          <el-input v-model="markName" autocomplete="off" style="width:230px" maxlength="10"></el-input>
          <el-color-picker style="margin-left: 5px"
                           v-model="colorBg"
                           :predefine="colorArray">
          </el-color-picker>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelLabel" size="small">取 消</el-button>
          <el-button type="primary" @click="addMark" size="small">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="cancel_show" center append-to-body width="500px" :close-on-click-modal="false">
        <p slot="title" class="dialog-title">取消跟进客户</p>
        <div style="font-size:13px;text-align: center;line-height: 20px">
          <p style="font-weight: 600">您确定要取消跟进如下{{selectName.length}}个客户吗？</p>
          <p style="margin-top: 5px">
            <span style="font-weight: 600" v-for="(item,index) in selectName" :key="index"> <span
              v-if="index != 0">,</span>{{item}} </span>
          </p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel_show = false" size="small">取 消</el-button>
          <el-button type="primary" @click="cancelCust" :loading="loading" size="small">取消跟进</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="delete_show" center append-to-body width="400px" :close-on-click-modal="false">
        <p slot="title" class="dialog-title">删除客户</p>
        <div style="font-size:13px;text-align: center;line-height: 20px">
          <p style="font-weight: 600">您确定要删除如下{{selectName.length}}个客户吗？</p>
          <p style="margin-top: 5px" class="moreLine">
            <span style="font-weight: 600" v-for="(item,index) in selectName" :key="index"> <span
              v-if="index != 0">,</span>{{item}} </span>
          </p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="delete_show = false" size="small">取消</el-button>
          <el-button type="primary" @click="deleteCust" size="small">确定</el-button>
        </div>
      </el-dialog>

      <drawer v-if="drawerShow" :custId="nowId" :visible="visShow" @callback="closeDrawer" type="1"></drawer>

      <el-dialog
        :visible.sync="send_mail_show"
        @close="closeMail"
        width="80%">
        <Mail :model="true" @closeMail="closeMail" :targetEmail="defaultEmail" v-if="showMail"></Mail>
      </el-dialog>

      <DialogImport ref="dialogImport" @updateCust="updateCust"></DialogImport>
      <!--选择联系人-->
      <DialogLinker ref="dialogLinker"></DialogLinker>
    </div>
  </div>
</template>
<script>
    import tableTemplate from '@/components/customer/tableTemplate'
    import editCompany from '@/components/customer/company/index'
    import DialogImport from '@/components/customer/dialogImport'
    import DialogLinker from '@/components/customer/dialogLinker'
    import Mail from '@/views/mail/draft/edit'
    import {
        queryMyCust,
        lightCustInfo,
        queryCustMark,
        saveCustMark,
        deleteBatchCust,
        markCust,
        moveGroup,
        mergeCust,
        queryCust,
        shareCust,
        transferCust,
        queryCustType,
        getCustField,
        setCustField,
        getFlowUp,
        cancelFlowUp,
        delMarkCust,
        fullNameStore,
        changeRate,
        findUserByCrop,
        canCelCust
    } from '@/api/customer'
    import {getCustomerEmail} from '@/util/util'
    import drawer from './template/drawer'
    import {mapGetters, mapState} from "vuex"

    export default {
        data() {
            return {
                empty: './img/empty.png',
                load: false,
                jurisdiction: {
                    customer_edit: false,
                    customer_move: false,
                    customer_senMail: false,
                    customer_exchange: false,
                    customer_merge: false,
                    customer_share: false,
                    customer_transfer: false,
                    customer_cancel: false,
                    customer_delete: false,
                    customer_add: false,
                    customer_unlabel: false,
                    customer_grade: false,
                }, // 客户权限按钮
                drawerShow: false, // 详情页组件
                visShow: false, // 抽屉显隐
                nowId: '', // 当前客户id
                markDialog: false,
                isActive: true, // 默认隐藏
                showMail: false, // 默认显示发邮件
                purchase: true, // 采购供应切换
                send_mail_show: false, // 发送邮件弹框
                dialogVisible: false, // 右侧详情页
                edit_boolean: true, // 是否可以编辑
                label_show: false, // 新建标签的显示
                colorBg: '', // 背景选择颜色
                colorArray: ['#000000', '#BE5957', '#DA762F', '#139891', '#4A669F', '#595AC1', '#333333', '#E63C38', '#EC994D', '#5DBD7F', '#5B87ED', '#8D50BF', '#7B8291', '#F07A79', '#E3AE02', '#7EC65E', '#45A7EE', '#ACACAC'],
                editCom_show: false, // 修改客户弹框
                editCom_title: '编辑客户',
                centerDialogVisible: false, // 表头显示
                checkList: [], // 显示表头数组
                headerList:[], // 选中表头集合，用来遍历表头
                copyCheckList: [], // 深拷贝复制选择
                edittacts_show: false,
                markList: [], // 标记为
                showlist: [], // 显示表头数组
                dialogFormVisible: false,
                select_num: 0, // 多选的条数
                total: 0, // 总条数
                nowPage: 1, // 当前页
                input: '', // 输入框
                value: '',
                tableData: [],
                activeName: 'second',
                size: 'medium',
                selectData: [], // 多选数组
                selectIds: [], // 多选ids
                selectName: [], // 多选姓名
                selectRow: [],
                signDialog: false,
                transferDialog: false,
                selectTitle: '', // 树形select框title
                shareDialog: false,
                cancel_show: false,
                selectionId: '',
                selectValue: '',
                mergeOptions: [],
                senior: false,
                second_menu1: false,
                second_menu2: false,
                lableList: [],
                groupingList: [],
                group_num: 0,
                lable_num: 0,
                delete_show: false,
                nowData: '', // 当前右键所选中的数据
                nowSize: 10, //当前页显示条数
                markName: '',
                delete_type: '', // 删除状态，控制单删还是多选删除
                markDto: [], // 标记为的数组
                markArr: [], // 标记id组
                editData: '',
                followContent: '', // 跟进内容
                editCon_title: '',
                contactsData: '',
                contactsIndex: '', // 当前编辑联系人的索引
                userOptions: [], // 当前企业下所有用户
                shareValue: [], // 共享数组
                transferValue: [], // 分享数组
                custTypeOptions: [], // 当前用户的所有分组
                isPublic: '', // 是否是公海客户
                custType: '', // 客户分组类型
                props: {
                    checkStrictly: true,
                    value: "id",
                    label: "text",
                    children: "children"
                },
                isClearable: true, // 可清空（可选）
                isAccordion: true, // 可收起（可选）
                sortField: '', // 排序的id
                sortType: '', // 排序方式 （正序倒序）
                treeShow: true,
                defaultEmail: [],
                priKey: '', // 合并客户的主要客户
                typeids: [], // 分组id集合
                lables: [], // 标签id集合
                userTree: [], // 共享，转移数组
                flowUpList: [], // 跟进记录信息
                flowUpTotal: 0, // 跟进记录条数
                flowUpContent: '', // 跟进记录搜索
                tiemOptions: [{
                    value: 'ASC',
                    label: '时间正序'
                },
                    {
                        value: 'DESC',
                        label: '时间倒序'
                    },
                ],
                flowUpType: 0, // 默认事类型为全部
                timeSort: 'DESC', // 默认时间顺序为倒序
                custId: '',
                companyShow: false,   // 强制刷新组件的方法
                tips: [],
                manager: '',
                shareArr: [], // 分享的数组
                transferArr: '', // 转移的数组
                typeId: this.$route.params.typeId ? this.$route.params.typeId : '',
                tableHeight: document.documentElement.clientHeight - 177,
                groupId:[], // 分组id
                loading:false
            }
        },
        components: {
            editCompany,
            Mail,
            drawer,
            DialogImport,
            DialogLinker,
            tableTemplate
        },
        watch: {
            selectData(value) {
                this.selectRow = []
                if (value.length > 0) {
                    value.forEach((item) => {
                        this.selectRow.push(this.tableData.indexOf(item))
                    })
                }
            },
            flowUpType(value) {
                this.nowPage = 1
                getFlowUp(1, 10, this.nowData.id, this.flowUpContent, this.timeSort, value).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            },
            timeSort(value) {
                this.nowPage = 1
                getFlowUp(1, 10, this.nowData.id, this.flowUpContent, value, this.flowUpType).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            },
            '$route': function (to) {
                this.typeId = to.params.typeId
                this.input = ''
                this.nowPage = 1
                this.nowSize = 10
                this.init()
            },
            senior(value) {
                this.tableHeight = value ? document.documentElement.clientHeight - 227 :document.documentElement.clientHeight - 177
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(["permission"])
        },
        created() {
            this.jurisdiction = this.vaildData(this.permission)
            getCustField().then(res => { // 列表显示字段
                if (res.data.success) {
                    res.data.data.forEach(value => {
                        value.show = value.isshow == 0 ? false : true
                        if (value.show) {
                            this.checkList.push(value.name)
                            this.headerList.push(value)
                        }
                    })
                    this.showlist = res.data.data
                    this.copyCheckList = this.checkList
                    this.load = true
                }
            })
            findUserByCrop().then(res => { // 公司下所有员工
                if (res.data.success) {
                    this.userTree = res.data.data
                }
            })
            this.init()
            queryCustMark().then((res) => { // 请求标记的数组
                this.markList = res.data.data
                this.lableList = JSON.parse(JSON.stringify(res.data.data))
                var obj = {
                    corpid: "000000",
                    custid: "",
                    id: -1,
                    markName: "+新建标签",
                }
                this.lableList.push(obj)
            })
            queryCustType().then(res => { // 当前用户的分组
                this.custTypeOptions = res.data.data
                this.$nextTick(() => {
                    if (this.custType != undefined) {
                        this.typeids.push(this.custType)
                    }
                })

            })
            fullNameStore().then(res => { // 输入建议
                this.tips = res.data.data
            })
        },
        mounted() {
            //新建客户信息
            if (this.$route.query.type) {
                this.showlog();
            }
            window.onresize = () => {
                this.$nextTick(() => {
                    this.tableHeight = this.senior ? document.documentElement.clientHeight - 227 :document.documentElement.clientHeight - 177
                })
            }

            this.bus.$on('updataCustInfo', () => {
                this.init();
            })

        },
        methods: {
            toDetail(id){
                sessionStorage.setItem("lastpathcus", this.$route.fullPath)
                this.$router.push(`/customer/myDetail/${id}`);
            },
            updateCust() {
                this.init()
                this.bus.$emit('updataCustMenu')
            },
            cancelCustShare(id) { // 取消共享
                this.$confirm('此操作将取消该客户共享, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    console.log(id)
                    canCelCust(id).then(res => {
                        if(res.data.success) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            });
                            this.init()
                        }
                    })
                })
            },
            senMail() { // 发送邮件
                if (this.common.emailList.length == 0) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">您需要先绑定自己的常用邮箱到我们的平台，才可以使用邮件模块功能哦！</p>\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">点击下方的按钮即可立即去绑定。</p>\n' +
                        '      </div>', '邮箱绑定提醒', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '去绑定',
                        cancelButtonText: '取 消',
                    }).then(() => {
                        this.$store.commit('SET_CURRENTSETFRAG', 'eight')
                        this.$router.push('/mail/administration');
                    }).catch(() => {
                    })
                    return;
                } else {
                    this.$refs.dialogLinker.init(this.selectData)
                }
            },
            dealingsMail() { // 来往邮件
                this.getCustomerInfo()
            },
            init() { // 初始化，获得新数据
                queryCustMark().then((res) => { // 请求标记的数组
                    this.markList = res.data.data
                    this.lableList = JSON.parse(JSON.stringify(res.data.data))
                    var obj = {
                        corpid: "000000",
                        custid: "",
                        id: -1,
                        markName: "+新建标签",
                    }
                    this.lableList.push(obj)
                })

                queryMyCust(this.$route.params.typeId, this.input, this.lables.toString(), this.typeids.toString(), this.nowPage, this.nowSize, this.sortField, this.sortType)
                    .then(res => { // 查询客户列表
                        if (res.data.success) {
                            this.tableData = res.data.data.records
                            this.total = res.data.data.total // 总页数
                            this.nowPage = res.data.data.current // 当前页数
                        }
                    })
            },
            cancelMark() { // 标记为弹框关闭
                this.markDialog = false
                this.markArr = []
            },
            cancelLabel() { // 标签弹框关闭
                this.label_show = false
                this.markName = ''
                this.colorBg = ''
            },
            querySearch(queryString, cb) {
                var tips = this.tips;
                var results = queryString ? tips.filter(this.createFilter(queryString)) : tips;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            changeRate(value, rate) { // 更改评级
                console.log(rate,value)
                changeRate(value, rate).then(res => {
                    if (res.data.success) {
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        })
                        this.init()
                    }
                })
            },
            createFilter(queryString) { // 搜索框过滤
                return (restaurant) => {
                    return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            replace() {
                var str = this.input
                this.input = str.replace(/\<|\>/g, '')
            },
            unlabel(custId, markId) { // 取消标签
                delMarkCust(custId, markId).then((res) => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: '删除标签成功'
                        })
                        this.init()
                    }
                })
            },
            openAddMark() {
                if (this.markArr.includes(-1)) {
                    this.markArr = []
                    this.label_show = true
                    this.markDialog = false
                }
            },
            custSaveMark() {
                this.loading = true
                let arr = []
                this.selectData.forEach(value => {
                    arr.push(value.id)
                })
                if (this.markArr.length > 0) {
                    markCust(arr.toString(), this.markArr.join(',')).then(res => {
                        if (res.data.success) {
                            this.markArr = []
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.loading = false
                            // 重新请求数据
                            this.init()
                        }
                    }).catch(() => {
                        this.loading = false
                    })
                }
                this.markDialog = false
            },
            custShow() { // 更改客户表头设置
                this.loading = true
                this.showlist.forEach((value) => {
                    if (this.copyCheckList.indexOf(value.name) > -1) {
                        value.isshow = 1 // 更改为true
                    } else {
                        value.isshow = 0 //跟改为false
                    }
                })
                setCustField(this.showlist).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        getCustField().then(res => { // 列表显示字段
                            if (res.data.success) {
                                this.checkList = []
                                this.headerList = []
                                res.data.data.forEach(value => {
                                    value.show = value.isshow == 0 ? false : true
                                    if (value.show) {
                                        this.checkList.push(value.name)
                                        this.headerList.push(value)
                                    }
                                })
                                this.$nextTick(() => {
                                    this.showlist = res.data.data
                                    this.copyCheckList = this.checkList
                                })
                            }
                        })
                        this.loading = false
                        this.centerDialogVisible = false
                    }
                }).catch(()=> {
                    this.loading = false
                })
            },

            closeCustShow() { // 取消客户表头设置
                this.centerDialogVisible = false
                this.copyCheckList = this.checkList
            },

            cancelCust() { // 取消跟进客户
                this.loading = true
                cancelFlowUp(this.selectIds.toString()).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.loading = false
                        this.cancel_show = false
                        this.bus.$emit('updataCustMenu')
                        this.init()
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            mergeCust() { // 合并客户
                this.loading = true
                var topid = ''
                this.selectData.forEach(value => {
                    if (value.fullname == this.priKey) {
                        topid = value.id
                    }
                })
                this.selectIds.unshift(topid)
                mergeCust(this.selectIds.toString()).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.loading = false
                        this.bus.$emit('updataCustMenu')
                        this.signDialog = false
                        this.init()
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            toMail() { // 跳转到往来邮件
                this.$router.push(`/mailCustomer/${this.nowData.id}`)
            },
            closeMail() {
                this.showMail = false
                this.send_mail_show = false
            },
            changeGroup(type) {
                if(!type && this.groupId.length > 0) {
                    if(this.selectData.length > 0) {
                        var ids = []
                        this.selectData.forEach(value => {
                            ids.push(value.id)
                        })
                        moveGroup(ids.toString(), this.groupId[this.groupId.length - 1]).then(res => {
                            if (res.data.success) {
                                this.$message({
                                    type: "success",
                                    message: res.data.msg
                                })
                                this.groupId = []
                                this.$nextTick(() => {
                                    this.bus.$emit('updataCustMenu')
                                    this.init()
                                })
                            } else {
                                this.$message({
                                    type: "success",
                                    message: res.data.msg
                                })
                            }
                        })
                    } else {
                        this.$message({
                            type: "success",
                            message: '请选择要移动的客户和分组'
                        })
                    }
                }
            },
            sortChange(order) { // sort 排序发生变化
                switch (order.prop) {
                    case 'light':
                        this.sortField = 'Light' // 标记
                        break;
                    case 'city':
                        this.sortField = 'country_icon' // 城市
                        break;
                    case 'talkNum':
                        this.sortField = 'talk_num' // 沟通次数
                        break;
                }

                if (order.order == 'ascending') {
                    this.sortType = 'ASC'
                } else {
                    this.sortType = 'Desc'
                }
                this.init()
            },
            moveCust(item) { // 移动客户分组
                moveGroup(this.nowData.id, item.id).then(res => {
                    if (res.data.success) {
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        })
                        this.bus.$emit('updataCustMenu')
                    }
                })
                //    刷新左侧菜单

            },
            sharedCust() { // 共享
                this.loading = true
                this.shareDialog = false
                let arr = []
                if (this.shareArr) {
                    this.selectData.forEach(value => {
                        arr.push(value.id)
                    })
                    shareCust(arr.toString(), this.shareArr.toString()).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.loading = false
                            this.shareArr = []
                            this.bus.$emit('updataCustMenu')
                            this.init()
                        }
                    }).catch(() => {
                        this.loading = false
                    })
                }
            },
            cancelShare() {
                this.shareDialog = false
                this.shareArr = []
            },
            cancelTransfer() { // 取消转移
                this.transferDialog = false
                this.transferArr = ''
            },
            transferCust() { // 转移
                this.loading = true
                let arr = []
                this.transferDialog = false
                if (this.transferArr) {
                    this.selectData.forEach(value => {
                        arr.push(value.id)
                    })
                    transferCust(arr.toString(), this.transferArr).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.loading = false
                            this.bus.$emit('updataCustMenu')
                            this.init()
                        }
                    }).catch(() => {
                        this.loading = false
                    })
                }
            },
            addMark() { // 新增标签
                saveCustMark(this.colorBg, this.markName).then((res) => {
                    if (res.data.success) {
                        this.markName = ''
                        this.colorBg = ''
                        this.label_show = false

                        queryCustMark().then((res) => { // 请求标记的数组
                            this.lableList = res.data.data
                            var nowMarkId = this.lableList[this.lableList.length - 1].id

                            var arr = []
                            this.selectData.forEach(value => {
                                arr.push(value.id)
                            })

                            markCust(arr.toString(), nowMarkId).then(res => {
                                this.markDto = []
                                this.markArr = []
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg
                                })
                                // 重新请求数据
                                var obj = {
                                    corpid: "000000",
                                    custid: "",
                                    id: -1,
                                    markName: "+新建标签",
                                }
                                this.lableList.push(obj)


                                this.init()
                            })
                        })
                    }
                })
            },
            checkbox(event, value, arr) { // checktbox 点击
                if (value == 'grouping') {
                    if (this.typeids.length == arr.length) {
                        this.typeids = []
                    } else {
                        this.typeids = []
                        arr.forEach((key) => {
                            this.typeids.push(key.id)
                        })
                    }
                } else {
                    if (this.lables.length == arr.length) {
                        this.lables = []
                    } else {
                        this.lables = []
                        arr.forEach((key) => {
                            this.lables.push(key.id)
                        })
                    }
                }
                this.search() // 点击进行高级搜索
            },
            active(event, value, item) { // button 点击变色
                if (value == 'grouping') {
                    if (this.typeids.indexOf(item) > -1) {
                        this.typeids.forEach((key, index) => {
                            if (key == item) {
                                this.typeids.splice(index, 1)
                            }
                        })
                    } else {
                        this.typeids.push(item)
                    }
                } else {
                    if (this.lables.indexOf(item) > -1) {
                        this.lables.forEach((key, index) => {
                            if (key == item) {
                                this.lables.splice(index, 1)
                            }
                        })
                    } else {
                        this.lables.push(item)
                    }
                }
                this.search() // 点击进行高级搜索
            },
            star(value, index) { // 点亮改变状态
                let type = ''
                if (value == 0) {
                    type = 1
                } else {
                    type = 0
                }
                lightCustInfo(index, type).then(() => {
                    this.init()
                })
            },
            show_editContacts(item, index) {
                if (item) {
                    this.editCon_title = '编辑联系人'
                    this.contactsIndex = index
                    this.contactsData = item
                } else {
                    this.editCon_title = '新增联系人'
                    this.contactsData = {
                        'firstName': '',
                        'lastName': '',
                        'email': '',
                        'postType': '',
                        'telFax': ''
                    }
                    this.contactsIndex = ''
                }
                this.edittacts_show = true
            },
            toDetails() {//  跳转到详情
                this.$router.push({path: '/customer/details'})
            },
            search() { // 搜索
                this.nowPage = 1
                this.init()
            },
            deleteCust() { // 删除
                let removeArr = []
                this.selectData.forEach(value => {
                    removeArr.push(value.id)
                })
                deleteBatchCust(removeArr).then((res) => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.bus.$emit('updataCustMenu')
                        this.delete_show = false
                        this.init()
                    }
                })
            },
            updataCompany(value) { // 编辑弹框的显示与隐藏
                if (value) {
                    this.init()
                }
                this.custId = ''
                this.$refs.editCompany.dialogFrom = false
            },
            editlog() { // 打开客户编辑弹框
                this.custId = this.selectData[0].id
                this.editCom_title = '编辑客户'
                this.$nextTick(() => {
                    this.$refs.editCompany.getInit(this.custId);
                })
            },
            changeCheck(value) { // 设置公司名称为必选
                if (value.indexOf('客户名称') < 0) {
                    this.checkList.push('客户名称')
                }
                // this.checkList.push('公司名称')
            },
            advancedSearch() { // 高级搜索的显示与隐藏
                this.senior = !this.senior
            },
            selectList(selection) { // table的全选
                if (selection.length == 1) {
                    this.edit_boolean = false
                } else {
                    this.edit_boolean = true
                }
                this.select_num = selection.length
                this.selectData = selection
                this.selectIds = []
                this.selectName = []
                this.selectData.forEach((value) => {
                    this.selectIds.push(value.id)
                    this.selectName.push(value.fullname)
                })
                this.priKey = this.selectName[0]
            },
            rowClass({row, rowIndex}) { // table选中后的样式
                if (this.selectRow.includes(rowIndex)) {
                    return {
                        "background-color": "#E9F3FD",
                        "color": "#409EFF"
                    }
                }
            },
            handleSizeChange(size) { // 改变每页条数
                this.nowPage = 1
                this.nowSize = size
                this.init()
            },
            handleCurrentChange(page) {
                this.nowPage = page // 当前页设置
                this.init()
            },
            showlog() { // 客户的显示
                this.$nextTick(() => {
                    this.editCom_title = "新增客户"
                    this.custId = '';
                    this.$refs.editCompany.addInit()
                })
            },
            changeSelect(value) { // 更多的选项
                if (this.selectData.length === 0) {
                    let message
                    switch (value) {
                        case '2':
                            message = '标记为'
                            break
                        case '3':
                            message = '合并'
                            break
                        case '4':
                            message = '共享'
                            break
                        case '5':
                            message = '转移'
                            break
                        case '6':
                            message = '取消跟进'
                            break
                        case '7':
                            message = '删除'
                            break
                    }
                    this.$message({
                        message: `请选择您要${message}的客户`,
                        type: "success"
                    })
                } else {
                    switch (value) {
                        case '2':
                            this.markDialog = true
                            break
                        case '3':
                            this.signDialog = true
                            break
                        case '4':
                            this.shareDialog = true
                            this.selectTitle = "共享客户至以下用户"
                            break
                        case '5':
                            this.transferDialog = true
                            this.selectTitle = "转移客户至以下用户"
                            break
                        case '6':
                            this.cancel_show = true
                            break
                        case '7':
                            this.delete_type = 'complex' // 多选删除
                            this.delete_show = true
                            break
                    }
                }
            },
            //获取客户信息
            getCustomerInfo() {
                queryCust(this.selectIds[0]).then(res => {
                    if (res.data.success) {
                        let link = res.data.data.custLinkDtos;
                        let result = []
                        if (link.length > 0) {
                            link.map(item => {
                                result.push(item.email)
                            })
                            getCustomerEmail(result,{userId:this.$route.params.userId},1);//获取往来邮件
                        } else {//没有邮箱 - 不需要跳转
                            this.$message({
                                message: '该用户未绑定邮箱，暂无往来邮件',
                                type: "success"
                            });
                        }
                    }
                })
            },
            preview(item, column, event) { // 右侧抽屉打开
                if (event.target.tagName !== 'I') {
                    this.nowId = item.id
                    this.visShow = true
                    this.drawerShow = true
                }
            },
            closeDrawer() {
                this.visShow = false
                this.drawerShow = false
            },
            floeUpChangePage(page) { // 跟进记录翻页
                this.nowPage = page
                getFlowUp(page, 10, this.nowData.id, this.flowUpContent, this.timeSort, this.flowUpType).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            },
            searchFlowUp() {
                this.nowPage = 1
                getFlowUp(1, 10, this.nowData.id, this.flowUpContent, this.timeSort, this.flowUpType).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            }
        },
    }
</script>

<style lang="scss">
  .custBox {
    .el-table__header-wrapper {
      background: rgb(234, 240, 246);
      height: 35px;
      line-height: 35px;
    }
  }

  .el-table__header {
    width: 100% !important;
  }

  .el-table__body {
    width: 100% !important;
  }

  .cell {
    .el-rate__icon {
      font-size: 18px;
    }
  }

  .tag {
    .el-icon-close {
      color: white !important;
    }
  }
</style>

<style lang="scss" scoped>
  @import "../../styles/customer";
</style>


